<template>
  <div>
    <div class="mb-[20px] bg">
      <div class="line_title mb-[20px] flex items-center">席位控制</div>
      <div style="display: flex; align-items: center">
        <div class="state">
          <span class="title text-sm">坐席状态：</span>
          <div
            style="
              padding: 4px 30px 4px 0;
              border-radius: 6px;
              display: flex;
              line-height: 20px;
            "
            :class="[
              state == 0
                ? 'bg-[#f7e5d1] text-[#e5902d]'
                : 'bg-[#d2e1f7] text-[#0d6efd]'
            ]"
          >
            <div>
              <el-dropdown>
                <span
                  :class="[
                    state == 0
                      ? 'bg-[#f7e5d1] text-[#e5902d]'
                      : 'bg-[#d2e1f7] text-[#0d6efd]',
                    'el-dropdown-link '
                  ]"
                >
                  {{ state == 0 ? "忙碌" : "空闲" }}
                  <el-icon>
                    <CaretBottom />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="clickDropdown(0)"
                      >忙碌</el-dropdown-item
                    >
                    <el-dropdown-item @click="clickDropdown(1)"
                      >空闲</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            |
            <div class="ml-[20px] text-sm">{{ formatTime(stateTime) }}</div>
          </div>
        </div>
        <div class="title text-sm">
          针对群呼：
          <el-dropdown>
            <span class="call_line">
              {{ callType1 == 0 ? "已迁入" : "已迁出" }}
              <el-icon>
                <CaretBottom />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="changeCall(0)"
                  >已迁入</el-dropdown-item
                >
                <el-dropdown-item @click="changeCall(1)"
                  >已迁出</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
    <div class="mb-[20px] bg">
      <div class="line_title mb-[20px] flex items-center">通话控制</div>
      <div style="display: flex" class="mb-[30px] items-center">
        <div class="text-sm">
          <span>手机号：</span>
          <el-input
            v-model="phone"
            maxlength="11"
            style="width: 240px"
            placeholder="请输入手机号"
            clearable
            @input="reInstance"
          />
        </div>
        <div class="ml-[40px] text-sm" v-if="elapsedTime">
          通话时长：{{ formatTime(elapsedTime) }}
        </div>
        <div class="ml-[40px] text-sm" v-if="waitTime">
          等待时长：{{ formatTime(waitTime) }}
        </div>
        <div class="ml-[40px] text-sm" v-if="callResult">
          失败/挂断原因：{{ callResult}}
        </div>
      </div>
      <template v-if="permissions.is_callMark">
        <el-button
          :type="callStatus==='talking'?'success':'primary'"
          round
          @click="changePhone"
          :disabled="callStatus !== 'unCall' && callStatus !== 'breakCall'"
        >
          <el-icon class="el-icon--right"><Service /></el-icon>
          {{ btnText }}
        </el-button>
        <!-- <el-button
          type="primary"
          round
          v-if="
            [('OUT_CALL', 'OUT_CALLER_RING', 'OUT_CALLED_RING')].includes(
              callType
            )
          "
        >
          <el-icon class="el-icon--right"><Service /></el-icon>
          拨打中
        </el-button>
        <el-button type="primary" round v-if="callStatus == 'talking'">
          <el-icon class="el-icon--right"><Service /></el-icon>
          通话中...
        </el-button> -->
      </template>
      <el-button
        type="danger"
        round
        @click="hangupCall"
        v-if="permissions.is_callMark"
      >
        <el-icon class="el-icon--right"><Close /></el-icon>
        挂断电话
      </el-button>
      <el-button
        type="primary"
        round
        @click="acceptCall"
        v-if="permissions.is_callMark"
      >
        <el-icon class="el-icon--right"><DArrowRight /></el-icon>
        下一个
      </el-button>
      <el-button
        type="primary"
        round
        @click="holdTalking"
        v-if="permissions.is_callMark"
      >
        <el-icon class="el-icon--right"><VideoPause /></el-icon>
        通话保持
      </el-button>
    </div>
   <div class="bg" v-if="callStatus!='unCall'">
      <div>
        <div class="line_title mb-[20px] flex items-center">客户信息</div>
        <div>
          <div class="w-3/5 mb-[20px] text-sm">
           <el-descriptions v-if="groupCall && customerInfo.name" :column="2" border label-width="100px">
              <el-descriptions-item
                label="客户姓名"
                label-align="center"
                align="left"
                class-name="my-content"
                width="260px"
              >
                <div class="text-sm">{{customerInfo.name}}</div>
              </el-descriptions-item>
              <el-descriptions-item
                label="客户号码"
                label-align="center"
                align="left"
                class-name="my-content"
                width="260px"
              >
                <div class="text-sm">{{customerInfo.phone}}</div>
              </el-descriptions-item>
              <el-descriptions-item
                label="公司名称"
                label-align="center"
                align="left"
                class-name="my-content"
                width="260px"
              >
                <div class="text-sm">{{customerInfo.company_name}}</div>
              </el-descriptions-item>
            </el-descriptions>
            <div class="phone mt-[20px]" v-if="callAddress">归属地址：{{ callAddress}}</div>
            <div class="flex items-center mt-[20px]">
              <span class="title">客户状态：</span>
              <div class="w-1/3">
                <el-select v-model="customerStatus" placeholder="请选择">
                  <el-option label="接通未确定" value="unkown" />
                  <el-option label="无意向" value="refuse" />
                  <el-option label="有意向" value="intend" />
                </el-select>
              </div>
            </div>
          </div>
          <el-button
            type="primary"
            round
            @click="clickSave"
            v-if="permissions.is_callWork"
            >保存信息</el-button
          >
        </div>
        <!-- <div class="null">没有客户信息哟 ^_^</div> -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onUnmounted, computed, onMounted } from "vue";
// import Voice9 from 'voice9'
import {
  Service,
  VideoPause,
  DArrowRight,
  Close,
  CaretBottom,
  Phone
} from "@element-plus/icons-vue";
import { agentCallIn } from "@/api/outbound";
import { ElMessage } from "element-plus";
import { callOrder_orderMark } from "@/api/outbound";
import { message } from "@/utils/message";

import { useUserStoreHook } from "@/store/modules/user";
import { callTypeMap, otherCallTypeMap,caseMap } from "./shared";
import { http } from "@/utils/http";
import { baseUrlApi } from "@/api/utils";
import { callCallBack_customerDetail } from "@/api/customer"
/** 页面元素权限 */
const auth_element = computed(() => {
  return useUserStoreHook()?.auth_element;
});

const permissions = reactive({
  is_callMark: false, // 通话相关操作
  is_callWork: false // 话单标记
});

/** 筛选完-页面元素权限 */
if (auth_element.value) {
  // 查询 onpage 为 "/groupcallTask/workbenches/index" 的所有数据
  const homeData = Object.entries(JSON.parse(auth_element.value)).filter(
    ([key, value]) => value.onpage === "/groupcallTask/workbenches/index"
  );
  // 转换为对象形式
  const homeDataObj = Object.fromEntries(homeData);

  if (homeDataObj.callMark) permissions.is_callMark = true;
  if (homeDataObj.callWork) permissions.is_callWork = true;
}

const voice9 = new window.Voice9();
const phone = ref("");
const customerStatus = ref(""); // 客户状态
function getInitVoice() {
  agentCallIn().then(res => {
    if (res.code == 1000) {
      voice9.init(res.data);
      startTimer2();
      voice9.setBusy();
      voice9.addEventListener("logout", code => {
        ElMessage.error("未连接，链接失败, 错误code:" + code);
      });
    }
  });
}

function changePhone() {
  if (callStatus.value !== "unCall" && callStatus.value == "breakCall") return;

  if (groupCall.value) {
    voice9.acceptCall();
  } else {
    // 这里验证的是大陆11位手机号码 如有特殊需求需修改
    if (!/^1[3-9]\d{9}$/.test(phone.value))
      return ElMessage.error("请输入正确手机号");
    try {
      voice9.makeCallByFollowData(
        phone.value,
        JSON.stringify({ phone: phone.value })
      );
    } catch (err) {
      console.log(err);
    }
  }
}
function acceptCall() {
  voice9.acceptCall();
}
// 挂断电话
function hangupCall() {
  voice9.hangupCall();
}
//通话保持
function holdTalking() {
  voice9.holdTalking();
}
const customerInfo=ref({
  name:'',
  phone:'',
  company_name:''
})
const phone_info = ref();
const groupCall = ref(false);
const callStatus = ref("unCall"); // 通话状态  unCall：未拨打  inCall：拨打中  breakCall：拨打挂断  talking：通话中 other：其他状态
const callResult = ref(); // 通话结果
const callAddress = ref(); // 归属地址
const waitTime = ref(0); // 等待时长
const callType = ref(); // 监听type状态
const btnText = ref("拨打/接听");
let waitTimeTimer=null;
const startWaitTimeTimer = () => {
  waitTime.value = 0;
  waitTimeTimer=setInterval(() => {
    waitTime.value += 1000;
  }, 1000);
};
const stopWaitTimeTimer = () => {
  setTimeout(()=>{
    clearInterval(waitTimeTimer);
    waitTime.value=0;
  },500);
};
const test=()=>{
  groupCall.value = true;
  callStatus.value = "other";
  let url=`callCallBack/customerDetail?id=6288868707372363774&companyId=50`
  http.request("get", baseUrlApi(url),{}).then((res)=>{
     customerInfo.value.company_name=res.data?.company_name;
     customerInfo.value.name=res.data?.name;
     customerInfo.value.phone=res.data?.phone;
  })
}
const call_id = ref("")
const taskId = ref("")
//我记得之前写了一个监听报错的
voice9.addEventListener("message", data => {
  //判断 type 进行操作按钮显示，见 状态附录
  phone_info.value = data.data;

  callType.value = data.type;
  console.log(data.type,'data.type');
  if(["OUT_CALL", "OUT_CALLER_RING", "OUT_CALLED_RING"].includes(data.type)) {
    console.log(data,'data')
    if(callStatus.value!="inCall"){
      startWaitTimeTimer();
    }
    callAddress.value = data.data?.numberArea || "未知";
    callStatus.value = "inCall";
    btnText.value = "拨打中...";
  }
  else if (data.type == "TALKING") {
    call_id.value = data.data?.callId
    taskId.value = data.data.taskId
    console.log('call_id.value',call_id.value)
    callResult.value = null;
    btnText.value = "通话中...";
    callStatus.value = "talking";
    stopWaitTimeTimer();
    startTimer();
  }
  else if (data.type == "AFTER") {
    callStatus.value = "breakCall";
    callResult.value = caseMap[data.data.cause] || "未知状态";
    btnText.value = "拨打/接听";
    stopWaitTimeTimer();
    resetTimer();// 电话挂断
  }
  else if (otherCallTypeMap[data.type]) {
    callStatus.value = "other";
    callResult.value = null;
    btnText.value = otherCallTypeMap[data.type];
    stopWaitTimeTimer();
    // 判断群呼振铃
    if (data.type == "INBOUND_RING") {
      groupCall.value = true;
      callAddress.value = data.data?.numberArea || "未知";
      phone.value=data.data?.called;
      // let url=`callCallBack/customerDetail?id=${data.data.uuid1}`
      // http.request("get", baseUrlApi(url),{}).then((res)=>{
      //    customerInfo.value.company_name=res.data?.company_name;
      //    customerInfo.value.name=res.data?.name;
      //    customerInfo.value.phone=res.data?.phone;
      // })
      callCallBack_customerDetail({
        id:data.data.uuid1
      }).then(res=>{
        if(res.code == 1000){
          customerInfo.value.company_name=res.data?.company_name;
          customerInfo.value.name=res.data?.name;
          customerInfo.value.phone=res.data?.phone;
        }
      })
    }
  }
});
// 通话时间定时器
const isRunning = ref(false); // 是否正在计时
const elapsedTime = ref(0); // 已耗时（以毫秒为单位）
let intervalId = null; // setInterval的ID
const formatTime = milliseconds => {
  const seconds = Math.floor((milliseconds / 1000) % 60);
  const minutes = Math.floor((milliseconds / (1000 * 60)) % 60);
  const hours = Math.floor((milliseconds / (1000 * 60 * 60)) % 24);
  return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
};

// 启动计时器
const startTimer = () => {
  if (isRunning.value) return; // 如果已经在计时，直接返回
  isRunning.value = true; // 更新状态为“正在计时”
  intervalId = setInterval(() => {
    elapsedTime.value += 1000; // 每秒累加1000毫秒
  }, 1000);
};

// 暂停计时器
const pauseTimer = () => {
  isRunning.value = false; // 更新状态为“暂停”
  clearInterval(intervalId); // 清除计时器
};

// 重置计时器
const resetTimer = () => {
  isRunning.value = false; // 更新状态为“已重置”
  clearInterval(intervalId); // 清除计时器
  elapsedTime.value = 0; // 将已耗时设置为0
};
// 坐席状态选择
const state = ref(0); // 0 忙碌 1 空闲
const stateTime = ref(0);
function clickDropdown(e) {
  state.value = e;
  if (e == 1) {
    // 设置为空闲
    voice9.setReady();
    stateTime.value = 0;
  } else {
    voice9.setBusy();
    stateTime.value = 0;
  }
  startTimer2();
}
// 针对群呼状态
const callType1 = ref(0);
function changeCall(e) {
  callType1.value = e;
  if (e == 0) {
    getInitVoice();
  } else {
    voice9.logout();
  }
}
// 坐席状态时间定时器
const isRunning2 = ref(false); // 是否正在计时
let intervalId2 = null;
const startTimer2 = () => {
  if (isRunning2.value) return; // 如果已经在计时，直接返回
  isRunning2.value = true; // 更新状态为“正在计时”
  intervalId2 = setInterval(() => {
    stateTime.value += 1000; // 每秒累加1000毫秒
  }, 1000);
};
// 保存话单信息
function clickSave() {
  console.log('----',call_id.value)
  callOrder_orderMark({
    callId: call_id.value,
    intension: customerStatus.value,
    taskId:taskId.value
  }).then(res => {
    if (res.code == 1000) {
      message(`保存成功`, { type: "success" });
    }
  });
}

//------------2.电话上下电话切换控制
//2.1清空初始相关状态
const reInstance=()=>{
  if(groupCall.value==false){
    callStatus.value = "unCall";
    callAddress.value = null;
    waitTime.value = 0 ;
    callResult.value = null;
    btnText.value = "拨打/接听";
  }
};

onUnmounted(() => {
  voice9?.logout();
});
onMounted(() => {
  getInitVoice();
});
</script>

<style scoped>
:deep(.el-segmented--large .el-segmented__item) {
  /* padding: 0 31px; */
  border: 1px solid #f5f5f5;
}
:deep(.el-select--large .el-select__wrapper) {
  min-height: 30px !important;
}
.line_title::before {
  width: 4px;
  height: 15px;
  background: #1687fc;
  content: "";
  display: flex;
  margin-right: 7px;
}
.title {
  display: flex;
  align-items: center;
}
.state {
  display: flex;
  align-items: center;
  margin-right: 50px;
}
.el-dropdown-link {
  width: 90px;
  text-align: center;
  line-height: 20px;
}
.call_line {
  background: #ede9e9;
  padding: 10px 20px;
  border-radius: 6px;
  color: #666666;
}
.bg {
  background: var(--color-bg_color);
  padding: 20px;
}
</style>
